//
//  MainViewController.m
//  iFlick1.4
//
//  Created by vhly on 10-8-27.
//  Copyright 2010 xhzhang. All rights reserved.
//

#import "MainViewController.h"
#import "FlickrClient.h"

#import "ViewControllerChooser_iPhone.h"
#import "PhotoDetailViewController.h"

#import "PhotoItem.h"
#import "ItemStore.h"
#import "DataManager.h"

@implementation MainViewController

@synthesize strFrob;
@synthesize btnAuth;
@synthesize btnCamera;
@synthesize alertView;
@synthesize mytableView;

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
    }
    return self;
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithTitle:@"Login" style:UIBarButtonItemStyleBordered target:self action:@selector(authCheck:)];
	self.btnAuth = btn;
	[btn release];
	self.navigationItem.leftBarButtonItem = self.btnAuth;
	
	self.navigationItem.title = @"iFlick";
	
	if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
		self.btnCamera.enabled = NO;
	}
	
	UIButton *btnInfo = [UIButton buttonWithType:UIButtonTypeInfoLight];
	[btnInfo addTarget:self action:@selector(showSettings:) forControlEvents:UIControlEventTouchDown];
	UIBarButtonItem *bitem = [[UIBarButtonItem alloc] initWithCustomView:btnInfo];
	bitem.target = self;
	bitem.action = @selector(showSettings:);
	self.navigationItem.rightBarButtonItem = bitem;
	[bitem release];
	
	
	//FlickrClient *client = [FlickrClient getInstance];
//	if (![client isAuthorized]) {
//		[];
//	}
	// NSLog(@"%@",[DataManager applicationDocumentsDirectory]);
}

- (void)viewWillAppear:(BOOL)animated{
	[super viewWillAppear:animated];
	[self refreshAuthButton];
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

#pragma mark -
#pragma mark SettingViewController Display

- (IBAction)showSettings:(id)sender{
	ViewControllerChooser_iPhone *chooser = [ViewControllerChooser_iPhone getInstance];
	SettingViewController *svc = (SettingViewController *)[chooser choice:VC_SETTINGS];
	svc.delegate = self;
	svc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
	[self presentModalViewController:svc animated:YES];
}

- (void)settingViewControllerDidFinish:(SettingViewController *)controller{
	[controller dismissModalViewControllerAnimated:YES];
}

#pragma mark -
#pragma mark AuthorizationProgress

- (void)authCheck:(id)sender{
	FlickrClient *client = [FlickrClient getInstance];
	if ([client isAuthorized]) {
		// TODO User want to logout
		if (self.alertView == nil) {
			UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Confirm" message:@"Do you want to logout?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK",nil];
			self.alertView = av;
			[av release];
		}
		[self.alertView show];		
	}else {
		// TODO User want to login
		[NSThread detachNewThreadSelector:@selector(getFrobImpl) toTarget:self withObject:nil];
	}

}

#pragma mark -
#pragma mark PhotoTask

- (IBAction)addPhotoFromLibrary:(id)sender{
	if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
		if(pickerController == nil){
			pickerController = [[UIImagePickerController alloc] init];      // TODO 检查这个的释放情况
		}
		pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
		
		pickerController.delegate = self;
		
		[self.navigationController presentModalViewController:pickerController animated:NO];
	}
}

- (IBAction)addPhotoFromCamera:(id)sender{
	if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
		if(pickerController == nil){
			pickerController = [[UIImagePickerController alloc] init];      // TODO 检查这个的释放情况
		}
		pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
		
		pickerController.delegate = self;
		
		[self.navigationController presentModalViewController:pickerController animated:NO];
	}
}

- (IBAction)uploadPhotos:(id)sender{

}

#pragma mark -
#pragma mark UIImagePickerControllerDelegateImpl

/**
 * save Image Method support
 *
 *
 *
 */
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
	
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
	FlickrClient *client = [FlickrClient getInstance];
	
	if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
		BOOL sp = [DataManager getConfigBool:KEY_SAVE_PHOTO];
		if (sp) {
			UIImage *img = (UIImage *)[info objectForKey:UIImagePickerControllerOriginalImage];
			UIImageWriteToSavedPhotosAlbum(img,self,@selector(image:didFinishSavingWithError:contextInfo:),nil);
		}
	}
	
	
	[client addImage:info];
	[picker dismissModalViewControllerAnimated:NO];
	[self refreshList];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
	[picker dismissModalViewControllerAnimated:NO];
}

#pragma mark -
#pragma mark ProgressImpl

- (void)getFrobImpl{
	FlickrClient *client = [FlickrClient getInstance];
	self.strFrob = [client getFrob];
	if (self.strFrob) {
		NSString *ru = [client getAuthorizeURL:self.strFrob];
		[self performSelectorOnMainThread:@selector(showBrowser:) withObject:ru waitUntilDone:YES];
	}
}

- (void)showBrowser:(NSString *)url{
	ViewControllerChooser_iPhone *chooser = [ViewControllerChooser_iPhone getInstance];
	BrowserViewController_iPhone *br = (BrowserViewController_iPhone *)[chooser choice:VC_BROWSER];
	br.requestURL = url;
	br.delegate = self; // Auth finish and get Token
	[self.navigationController pushViewController:br animated:YES];
}

- (void)browseFinished{
	FlickrClient *client = [FlickrClient getInstance];
	[client getToken:self.strFrob];
	[self refreshAuthButton];
}


- (void)refreshAuthButton{
	FlickrClient *client = [FlickrClient getInstance];
	if ([client isAuthorized]) {
		self.btnAuth.title = @"Logout";
	}else {
		self.btnAuth.title = @"Login";
	}
}

- (void)refreshList{
	[self.mytableView reloadData];
}

#pragma mark -
#pragma mark UIAlertViewDelegateImpl

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
	// NSLog(@"Alert Button Index = %d",buttonIndex);
	// UIAlertView cancel button index is 0, other button index from 1.
	if (buttonIndex == 1) {
		// TODO Confirm to logout
		FlickrClient *client = [FlickrClient getInstance];
		[client logout];
		self.btnAuth.title = @"Login";
	}
}

#pragma mark -
#pragma mark UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
	FlickrClient *client = [FlickrClient getInstance];
	return [client imagesSize];
}

- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section{
	NSInteger ret = 0;
	FlickrClient *client = [FlickrClient getInstance];
	ItemStore *store = [client getItemStore:section];
	ret = [store count];
	return ret;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
	static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
	
	NSInteger section = indexPath.section;
	NSInteger row = indexPath.row;
	FlickrClient *client = [FlickrClient getInstance];
	ItemStore *store = [client getItemStore:section];
	PhotoItem *pi = (PhotoItem *)[store objectAtIndex:row];
	cell.textLabel.text = pi.title;
	cell.detailTextLabel.text = pi.description;
	
#define TES_1
#ifdef TES_1
	CGFloat ch = cell.frame.size.height;
	CGFloat iw = pi.origImage.size.width;
	CGFloat ih = pi.origImage.size.height;
	CGFloat sx = ch / iw;
	CGFloat sy = ch / ih;
	cell.imageView.image = pi.origImage;
	// 使用这种方法可以将图像缩小，但是比例需要检查
	cell.imageView.transform = CGAffineTransformMakeScale(sx, sy);
#else
	cell.imageView.image = pi.thumbImage;
#endif
	
	if (pi.status == ST_UPLOADED) {
		cell.accessoryType = UITableViewCellAccessoryCheckmark;
	}else {
		cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
	}

	
	return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
	FlickrClient *client = [FlickrClient getInstance];
	ItemStore *store = [client getItemStore:section];
	return store.title;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
	return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        //[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
		NSInteger section = indexPath.section;
		NSInteger row = indexPath.row;
		FlickrClient *client = [FlickrClient getInstance];
		ItemStore *store = [client getItemStore:section];
		[store removeObjectAtIndex:row];
		[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
		
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
		// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
	}   
}

#pragma mark -
#pragma mark UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
	ViewControllerChooser_iPhone *vc = [ViewControllerChooser_iPhone getInstance];
	PhotoDetailViewController *detail = (PhotoDetailViewController *)[vc choice:VC_DETAIL];
	[self.navigationController pushViewController:detail animated:YES];
}

/**
 * UITableView's accessoryButton Tapped, in section and row
 * @param tableView UITableView*
 * @param indexPath NSIndexPath* for UITableView
 */
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{
	
}

#pragma mark -

- (void)dealloc {
	[strFrob release];
	[btnAuth release];
	[alertView release];
	[pickerController release];
	[mytableView release];
	[btnCamera release];
    [super dealloc];
}


@end
